<template>
  <div class="user">
    <el-card class="box-card" v-if="status === 'index'">
      <el-row>
        <el-input v-model="searchParams.id" placeholder="请输入用户id" clearable style="width:200px" size="mini"></el-input>
        <el-input v-model="searchParams.mobile" placeholder="请输入手机号" clearable style="width:200px"
          size="mini"></el-input>
        <el-select v-model="searchParams.level" placeholder="请选择会员级别" clearable :style="{ width: '150px' }" size="mini">
          <el-option v-for="item in levelData" :key="item.id" :label="item.name" :value="item.level_id"></el-option>
        </el-select>
        <el-select v-model="searchParams.type" placeholder="请选择会员类型" clearable :style="{ width: '150px' }" size="mini">
          <el-option v-for="item in typeData" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <el-date-picker v-model="searchParams.startTime" type="datetime" placeholder="选择开始时间"
          :picker-options="pickerOptions" size="mini"></el-date-picker>
        <el-date-picker v-model="searchParams.endTime" type="datetime" placeholder="选择结束时间"
          :picker-options="pickerOptions" size="mini"></el-date-picker>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getData2"
          v-if="has('users/index')">搜索</el-button>
        <el-button type="info" icon="el-icon-refresh" size="mini" @click="reset"
          v-if="has('users/index')">重置</el-button>
      </el-row>
      <el-table :data="data.data"  v-loading="table_loading" style="width: 100%;margin:10px auto" size="mini"
        :header-cell-style="{ background: '#f3f8fe', color: '#333' }">
        <el-table-column prop="id" label="用户信息" align="center" width="160">
          <template fixed slot-scope="scope">
            <div style="display: flex;align-items: center;">
              <img :src="scope.row.avatar" :style="{ width: '50px', height: '50px', borderRadius: '5px' }"
                @click="bigImage(scope.row.avatar)" />
              <div>
                <div>{{ scope.row.nickname }}</div>
                <div>{{ scope.row.id }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.is_anchor == 1" style="color:red"></span>
            <span v-if="scope.row.is_agent == 1" style="color:green">推广员</span>
            <span v-if="scope.row.is_agent == 0 && scope.row.is_anchor == 0">普通用户</span>
          </template>
        </el-table-column>
        <el-table-column  prop="mobile" label="手机号" align="center"></el-table-column>
        <el-table-column label="用户级别" align="center">
          <template slot-scope="scope">
            <span style="text-decoration:underline;cursor: pointer;" @click="changeLevel(scope.row)">{{
              scope.row.level_name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="上级id" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.parent_id != 0" style="text-decoration:underline;cursor: pointer;"
              @click="changeParent(scope.row)">{{ scope.row.parent_id }}</span>
            <span v-else style="text-decoration:underline;cursor: pointer;" @click="changeParent(scope.row)">无</span>
          </template>
        </el-table-column>

        <el-table-column label="总流水" prop="account.total_pay" align="center">
        </el-table-column>
        <el-table-column label="总充值" prop="account.total_recharge" align="center">
        </el-table-column>
        <el-table-column label="金币" prop="account.balance" align="center">
        </el-table-column>
        <el-table-column label="钻石" prop="account.point" align="center">
        </el-table-column>
        <el-table-column label="成长值" prop="account.grow_value" align="center">
        </el-table-column>
        <el-table-column label="直推" prop="direct_reat" align="center">
          <template slot-scope="scope"> {{ scope.row.direct_reat }}% </template>
        </el-table-column>
        <el-table-column label="间推" prop="indirect_reat" align="center">
          <template slot-scope="scope">
            {{ scope.row.indirect_reat }}%
          </template>
        </el-table-column>

        <el-table-column prop="is_all_see" label="禁玩" align="center">
          <template slot-scope="scope">
            <el-switch v-if="scope.row.is_all_see != -1" @change="changeUserStatus(scope.row)" v-model="scope.row.is_all_see"
                       active-color="#13ce66" inactive-color="#ff4949" :active-value="activeValue"
                       :inactive-value="inactiveValue">
            </el-switch>
            <span v-if="scope.row.is_all_see == -1">已注销</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template slot-scope="scope">
            <el-switch v-if="scope.row.status != -1" @change="changeStatus(scope.row)" v-model="scope.row.status"
                       active-color="#13ce66" inactive-color="#ff4949" :active-value="activeValue"
                       :inactive-value="inactiveValue">
            </el-switch>
            <span v-if="scope.row.status == -1">已注销</span>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="注册时间" align="center"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="300">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="detail(scope.row.id)" v-if="has('users/show')">详情</el-button>
            <el-button type="primary" size="mini" @click="recharge(scope.row.id)"
              v-if="has('users/recharge')">充值</el-button>
            <el-button type="primary" size="mini" @click="deduct(scope.row.id)"
              v-if="has('users/deduct')">扣除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination background style="text-align:center;margin:20px 0;" :current-page="searchParams.page"
        :page-sizes="pageSizes" layout="total,prev, pager, next,sizes" :total="data.total" @size-change="changeSize"
        @current-change="changePage"></el-pagination>
    </el-card>
    <el-card v-if="status === 'add'">
      <div slot="header">
        <el-page-header @back="init" content="用户详情"></el-page-header>
      </div>
      <div class="user_detail">
        <el-card class="user_info">
          <div slot="header">
            用户信息
          </div>
          <el-form :model="editParams" label-width="120px">
            <el-form-item label="用户昵称">
              <el-input v-model="editParams.nickname"></el-input>
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="editParams.mobile" readonly></el-input>
            </el-form-item>
            <el-form-item label="OPENID">
              <el-input v-model="editParams.openid" readonly></el-input>
            </el-form-item>
            <el-form-item label="UNIONID">
              <el-input v-model="editParams.unionid" readonly></el-input>
            </el-form-item>
            <el-form-item label="用户上级">
              <el-input :value="editParams.parent ? editParams.parent.nickname : '无'" readonly></el-input>
            </el-form-item>

            <el-form-item label="头像">
              <el-image :src="editParams.avatar" style="width: 50px;height:50px"></el-image>
            </el-form-item>
            <el-form-item label="用户等级">
              <el-input v-model="editParams.level_id" readonly></el-input>
            </el-form-item>
            <el-form-item label="注册时间">
              <el-input v-model="editParams.created_at" readonly></el-input>
            </el-form-item>
            <el-form-item label="直推佣金">
              <el-input v-model="editParams.direct_reat"></el-input>
            </el-form-item>
            <el-form-item label="间推佣金">
              <el-input v-model="editParams.indirect_reat"></el-input>
            </el-form-item>
            <el-form-item label="主播">
              <el-select v-model="editParams.is_anchor" placeholder="主播" clearable :style="{ width: '150px' }">
                <el-option v-for="item in anchorData" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="状态">
              <el-select v-model="editParams.status" placeholder="状态" clearable :style="{ width: '150px' }">
                <el-option v-for="item in officialData" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="">
              <el-button type="primary" @click="updateSubmit()" v-if="has('users/update')">保存</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        <div class="account_fans">
          <el-card class="user_account">
            <div slot="header">
              账户信息
            </div>
            <el-form :model="editParams" label-width="0">
              <el-form-item label="">
                <el-input v-model="editParams.account.balance" readonly style="width:150px">
                  <template slot="prepend">金币</template>
                </el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input style="width:150px" v-model="editParams.account.point" readonly>
                  <template slot="prepend">钻石</template>
                </el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input :value="editParams.account.total_commission" readonly>
                  <template slot="prepend">累计佣金</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input :value="editParams.account.commission" readonly>
                  <template slot="prepend">当前佣金</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input v-model="editParams.account.used_commission" readonly>
                  <template slot="prepend">已提现佣金</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input v-model="editParams.account.grow_value" readonly>
                  <template slot="prepend">成长值</template>
                </el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input :value="editParams.account.total_pay" readonly>
                  <template slot="prepend">总流水</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
              <el-form-item label="">
                <el-input v-model="editParams.account.total_recharge" readonly>
                  <template slot="prepend">总充值</template>
                  <template slot="append">元</template>
                </el-input>
              </el-form-item>
            </el-form>
          </el-card>
        </div>
      </div>
    </el-card>


    <el-dialog title="充值" :visible.sync="rechargeStatus" @close="init">
      <el-form :model="rechargeParams" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="用户id">
          <el-input v-model="rechargeParams.user_id" readonly></el-input>
        </el-form-item>
        <el-form-item label="充值类型" prop="type">
          <el-select v-model="rechargeParams.type" placeholder="请选择充值类型">
            <el-option v-for="item in rechargeType" :key="item.id" :value="item.id" :label="item.title"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="优惠券" v-if="rechargeParams.type == 3">
          <el-select v-model="rechargeParams.coupon_id">
            <!-- :label="item.name + '——满' + item.min_amount + '减' + item.amount" -->
            <el-option v-for="item in couponData" :key="item.id" :value="item.id" :label="item.name +
              '—' +
              (item.min_amount > 0 ? '满' + item.min_amount : '无门槛') +
              '减' +
              item.amount
              "></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="反悔卡" v-if="rechargeParams.type == 5">
          <el-select v-model="rechargeParams.back_card_id">
            <el-option v-for="item in backCardData" :key="item.id" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="充值数量" prop="value">
          <el-input v-model="rechargeParams.value" autocomplete="off" type="number" min="1" max="100"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('form', 1)" v-if="has('users/recharge')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="扣除" :visible.sync="deductStatus" @close="init">
      <el-form :model="rechargeParams" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="用户id">
          <el-input v-model="rechargeParams.user_id" readonly></el-input>
        </el-form-item>
        <el-form-item label="扣除类型" prop="type" placeholder="请选择扣除类型">
          <el-select v-model="rechargeParams.type">
            <el-option v-for="item in deductType" :key="item.id" :value="item.id" :label="item.title"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="扣除数量" prop="value">
          <el-input v-model="rechargeParams.value" autocomplete="off" min="1"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit('form', 2)" v-if="has('users/recharge')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改等级" :visible.sync="levelStatus" @close="init">
      <el-form :model="levelParams" :rules="levelRules" ref="levelForm" label-width="120px">
        <el-form-item label="用户id">
          <el-input v-model="levelParams.user_id" readonly></el-input>
        </el-form-item>
        <el-form-item label="等级" prop="level_id">
          <el-select v-model="levelParams.level_id" placeholder="请选择等级">
            <el-option v-for="item in levelData" :key="item.id" :value="item.level_id" :label="item.name" @change="lvelChange"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeLevelSubmit('levelForm')" v-if="has('users/changeLevel')">确
          定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="修改上级" :visible.sync="parentStatus" @close="init">
      <el-form :model="parentParams" :rules="parentRules" ref="parentForm" label-width="120px">
        <el-form-item label="用户id">
          <el-input v-model="parentParams.user_id" readonly></el-input>
        </el-form-item>
        <el-form-item label="上级id" prop="parent_id">
          <el-input placeholder="请输入上级id" v-model="parentParams.parent_id"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="changeParentSubmit('parentForm')" v-if="has('users/changeParent')">确
          定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from "../../api/api.js";
export default {
  name: "user",
  data() {
    return {
      status: "index", // 页面控制
      fanStatus: false,
      data: [], // 表格诗句
      table_loading: true, // 表格加载中
      fansLoading: true,
      loading: false, //全局加载中
      levelData: [],
      pageSizes: [10, 20, 50, 100, 200, 500, 800, 1000, 2000], // 每页条数默认10
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      anchorData: [
        { id: 1, name: "是" },
        { id: 0, name: "否" }
      ],
      officialData: [
        { id: 1, name: "正常" },
        { id: 2, name: "注销" },
        { id: 0, name: "封禁" }
      ],
      typeData: [
        { id: 1, name: "普通用户" },
        { id: 2, name: "主播" },
        { id: 3, name: "推广员" },
      ],
      activeValue: 1,
      inactiveValue: 0,
      searchParams: {
        page: 1,
        limit: 10,
        id: "",
        level: "",
        type: "",
        mobile: ""
      },
      editParams: {
        account: {}
      },
      rechargeType: [
        { id: 1, title: "赠送金币" },
        { id: 2, title: "代充金币" },
        { id: 3, title: "优惠券" },
        { id: 4, title: "钻石" },
        { id: 5, title: "反悔卡" },
        { id: 6, title: "无限免抽卡" }
      ],
      deductType: [
        { id: 1, title: "金币" },
        { id: 4, title: "钻石" }
      ],
      deductTypes: [
        { id: 0, title: "金币" },
        { id: 1, title: "钻石" }
      ],
      rechargeStatus: false,
      deductStatus: false,
      rechargeParams: {},
      rules: {
        type: [{ required: true, message: "请选择充值类型", trigger: "blur" }],
        value: [{ required: true, message: "请输入充值数量", trigger: "blur" }]
      },
      levelRules: {
        level_id: [{ required: true, message: "请选择等级", trigger: "blur" }]
      },
      parentRules: {
        parent_id: [
          { required: true, message: "请输入上级id", trigger: "blur" }
        ]
      },
      couponData: [],
      backCardData: [],
      logData: { data: [] },
      logSearchParams: {
        // 搜索参数
        userId: "",
        levelId: "",
        catId: "",
        page: 1,
        limit: 10,
        challenge_box_id: "",
        startTime: "",
        endTime: ""
      },
      levelStatus: false,
      parentStatus: false,
      levelParams: {},
      parentParams: {}
    };
  },
  created() {
    this.getData2();
    this.getLevel();
    this.getCoupon();
    this.getBackCard();
  },

  methods: {
    lvelChange(e){
console.log(e)
    },
    changeStatus(e) {
      this.load();
      api.users
        .status(e.id, { status: e.status })
        .then(res => {
          this.unload();
          if (res.data.code === 200) {
            this.$message.success("保存成功");
            this.getData();
          }
        })
        .catch(error => {
          console.log(error);
        });
    },

    changeUserStatus(e){
      this.load();
      api.users
        .updateUserStatus(e.id, { status: e.is_all_see })
        .then(res => {
          this.unload();
          if (res.data.code === 200) {
            this.$message.success("保存成功");
            this.getData();
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    log(row) {
      this.logSearchParams.user_id = row.id;
      this.logTitle = row.name;
      this.status = "log";
    },
    // 修改等级弹窗
    changeLevel(item) {
      this.levelParams.user_id = item.id;
      this.levelParams.level_id = item.level_id;
      this.levelStatus = true;
    },
    // 修改上级弹窗
    changeParent(item) {
      this.parentParams.user_id = item.id;
      this.parentParams.parent_id = item.parent_id;
      this.parentStatus = true;
    },
    updateSubmit() {
      this.load();
      api.users
        .update(this.editParams.id, this.editParams)
        .then(res => {
          this.unload();
          if (res.data.code === 200) {
            this.$message.success(res.data.msg);
            this.detail(this.editParams.id);
            this.getData()
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    changeLevelSubmit(formName) {
      // 自动验证
      this.$refs[formName].validate((valid, error) => {
        if (valid) {
          this.load();
          api.users
            .changeLevel(this.levelParams.user_id, this.levelParams)
            .then(res => {
              this.unload();
              if (res.data.code === 200) {
                this.$message.success(res.data.msg);
                this.reset();
              }
            })
            .catch(error => {
              console.log(error);
            });
        } else {
          this.$message.error(Object.values(error)[0][0].message);
          return false;
        }
      });
    },
    changeParentSubmit(formName) {
      // 自动验证
      this.$refs[formName].validate((valid, error) => {
        if (valid) {
          this.load();
          api.users
            .changeParent(this.parentParams.user_id, this.parentParams)
            .then(res => {
              this.unload();
              if (res.data.code === 200) {
                this.$message.success(res.data.msg);
                this.reset();
              }
            })
            .catch(error => {
              console.log(error);
            });
        } else {
          this.$message.error(Object.values(error)[0][0].message);
          return false;
        }
      });
    },
    // 获取所有等级
    getLevel() {
      api.common
        .getUserLevel()
        .then(res => {
          if (res.data.code === 200) {
            this.levelData = res.data.data;
          }
        })
        .catch(error => { });
    },
    // 获取优惠券列表
    getCoupon() {
      api.common
        .getCoupon()
        .then(res => {
          if (res.data.code === 200) {
            this.couponData = res.data.data;
          }
        })
        .catch(error => { });
    },
    getBackCard() {
      api.common
        .getBackCard()
        .then(res => {
          if (res.data.code === 200) {
            this.backCardData = res.data.data;
          }
        })
        .catch(error => { });
    },
    // 加载中
    load() {
      this.loading = this.$loading({
        lock: true,
        text: "数据加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
    },
    // 取消加载
    unload() {
      this.loading.close();
    },
    getData2() {
      this.searchParams.page = 1;
      this.getData();
    },
    // 获取用户列表
    getData() {
      this.table_loading = true;
      api.users
        .index({ params: this.searchParams })
        .then(res => {
          if (res.data.code === 200) {
            this.table_loading = false;
            this.data = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 重置搜索参数重新搜索
    reset() {
      this.init();
      this.getData();
    },
    // 初始化
    init() {
      this.searchParams.id = "";
      this.searchParams.level = "";
      this.searchParams.type = "";
      this.searchParams.mobile = "";
      this.searchParams.startTime = "";
      this.searchParams.endTime = "";
      this.editParams = {
        account: {}
      };
      this.rechargeStatus = false;
      this.deductStatus = false;

      this.levelStatus = false;
      this.parentStatus = false;
      this.status = "index";

      this.rechargeParams = {
        type: "",
        user_id: "",
        coupon_id: "",
        value: ""
      };
      this.levelParams = {
        user_id: "",
        level_id: ""
      };
      this.parentParams = {
        user_id: "",
        parent_id: ""
      };
    },
    // 改变每页条数时
    changeSize(limit) {
      this.searchParams.limit = limit;
      this.getData();
    },
    // 改变当前页码时
    changePage(page) {
      this.searchParams.page = page;
      this.getData();
    },
    // 添加页面
    detail(id) {
      this.load();
      api.users
        .show(id, this.searchParams)
        .then(res => {
          this.unload();
          if (res.data.code === 200) {
            this.status = "add";
            this.editParams = res.data.data;
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    // 充值弹窗
    recharge(user_id) {
      this.rechargeStatus = true;
      this.rechargeParams.user_id = user_id;
    },
    // 扣除弹窗
    deduct(user_id) {
      this.rechargeParams.user_id = user_id;
      this.deductStatus = true;
    },
    // 充值/扣除
    submit(formName, type) {
      let type_name = type == 1 ? '充值' : '扣除';
      let type_id = type == 2 && this.rechargeParams.type == 4 ? 2 : this.rechargeParams.type;
      let title = type == 1 ? type_name + this.rechargeType[this.rechargeParams.type - 1].title : type_name + this.deductTypes[type_id - 1].title;
      let str = "您给用户ID:" + this.rechargeParams.user_id + " " + type_name + "数量:" + this.rechargeParams.value;
      this.$alert(str, title, {
        confirmButtonText: '确定',
        callback: action => {
          if (action !== 'confirm') return
          // 自动验证
          this.$refs[formName].validate((valid, error) => {
            if (valid) {
              if (this.rechargeParams.value < 0) {
                this.$message.error("请输入正确的数量");
                return;
              }
              if (this.rechargeParams.type == 3 && !this.rechargeParams.coupon_id) {
                this.$message.error("请选择优惠券");
                return;
              }
              this.load();
              if (type === 1) {
                api.users
                  .recharge(this.rechargeParams.user_id, this.rechargeParams)
                  .then(res => {
                    this.unload();
                    if (res.data.code === 200) {
                      this.$message.success(res.data.msg);
                      this.rechargeStatus = false;
                      this.deductStatus = false;
                      this.getData();
                    }
                  })
                  .catch(error => {
                    console.log(error);
                  });
              } else if (type === 2) {
                api.users
                  .deduct(this.rechargeParams.user_id, this.rechargeParams)
                  .then(res => {
                    this.unload();
                    if (res.data.code === 200) {
                      this.$message.success(res.data.msg);
                      this.rechargeStatus = false;
                      this.deductStatus = false;
                      this.getData();
                    }
                  })
                  .catch(error => {
                    console.log(error);
                  });
              }
            } else {
              this.$message.error(Object.values(error)[0][0].message);
              return false;
            }
          });
        }
      });
    }
  }
};
</script>

<style scoped lang="less">
.user {
  margin: 0 auto;

  .search {
    margin: 0 auto 10px auto;
  }

  .user_detail {
    display: flex;
    justify-content: space-between;

    .user_info,
    .account_fans {
      width: 48%;
    }

    .account_fans {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
  }
}
</style>
